#include "TLSContext.hpp"
#include "TLSConnection.hpp"
#include "TCPSocket.hpp"
#include <iostream>

#define PORT 4433

int main() {
    try {
        // 初始化 TLS 上下文，加载 SM2 证书和密钥
        TLSContext ctx(TLSContext::Role::Server, "sm2.cert.pem", "sm2.key.pem");

        // 创建 socket
        TCPSocket tcp_socket;
        tcp_socket.bindAndListen("", PORT);
        std::cout << "TLS server listening on port " << PORT << "...\n";

        // 接受连接
        int clientFd = tcp_socket.accept();
        
        TLSConnection conn(ctx.get(), clientFd);

        if (!conn.doHandshake(true)) {
            std::cerr << "Handshake failed\n";
            return 1;
        }

        // 读取客户端消息
        char buf[1024] = {0};
        int len = conn.read(buf, sizeof(buf));
        std::cout << "Client says: " << std::string(buf, len) << "\n";

        // 发送响应
        const char* reply = "Hello from server (TLS + SM2)";
        conn.write(reply, strlen(reply));

    } catch (const std::exception& ex) {
        std::cerr << "Fatal error: " << ex.what() << "\n";
        return 1;
    }

    return 0;
}
